package com.platinadesign.axa.view
{
	import com.greensock.TimelineLite;
	import com.greensock.TweenLite;
	import com.greensock.TweenMax;
	import com.platinadesign.axa.event.PageTurningEvent;
	
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Point;

	public class FlipingPage extends Sprite
	{
		public static const ONE_PAGE_TURNED : String = "MovingPage::FLIPING_FINISHED";

		private var _firstSide : BitmapData;

		private var _secondSide : BitmapData;

		private var _duration : Number;

		private var _toLeft : Boolean;

		public function FlipingPage( firstSide : BitmapData, secondSide : BitmapData, duration : Number, toLeft : Boolean )
		{
			_firstSide = firstSide;
			_secondSide = secondSide;
			_duration = duration;
			_toLeft = toLeft;

			drawPageSide( _firstSide, !_toLeft );
			if( !_toLeft )
			{
				this.rotationY = 180;
			}
		}

		/**
		 * 一个图片，翻篇过去后，会水平反转，所以要在中间状态时，进行反向处理，如果往左翻，则先反转，然后先翻过去，再返回来
		 * 如果往右翻，则后反转图片，这个逻辑靠_toLeft来进行判断，而这个值由最初的PAGEMANAGER提供，经由FLIPINGPAGES容器调用传递进来
		 */
		public function startFliping() : void
		{
			var targetAngle : int;

			if( !_toLeft )
			{
				this.rotationY = 180;
				targetAngle = 0;
			}
			else
			{
				targetAngle = 180;
			}
			const firstTween :TweenMax = new TweenMax( this, _duration * 0.5, { rotationY: 90,colorTransform:{brightness:0.7}, onComplete: firstCompleteHandler });
			const secondTween : TweenMax = new TweenMax( this, _duration * 0.5, { rotationY: targetAngle,colorTransform:{brightness:1}, onComplete: secondCompleteHandler });
			const tweenTimeLine : TimelineLite = new TimelineLite();
			tweenTimeLine.append( firstTween );
			tweenTimeLine.append( secondTween );
			tweenTimeLine.play();
		}

		public function depose() : void
		{
			_firstSide.dispose();
			_secondSide.dispose();
		}

		public function drawPageSide( side : BitmapData, invert : Boolean = false ) : void
		{
			const g : Graphics = this.graphics;
			g.clear();
			const matrix : Matrix = new Matrix();

			if( invert )
			{
				matrix.a = -1;
				matrix.tx = side.width;
			}
			g.beginBitmapFill( side, matrix, false, true );
			g.drawRect( 0, 0, side.width, side.height );
			g.endFill();
		}

		private function firstCompleteHandler() : void
		{
			drawPageSide( _secondSide, _toLeft );
		}

		private function secondCompleteHandler() : void
		{
			this.dispatchEvent( new Event( ONE_PAGE_TURNED ));
		}
	}
}